package com.ys.controller.api.finance;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ys.entity.finance.TcwExpenseSettlement;
import com.ys.util.admin.ConditionUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ys.config.MenuId;
import com.ys.entity.finance.TcwExpenseSettlement;
import com.ys.entity.sys.YsCol;
import com.ys.service.finance.TcwExpenseSettlementService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

/**
 * 费用结算单
 */
@Controller
@RequestMapping("/api/inter/tcwExpenseSettlement")
public class ApiInterTcwExpenseSettlementController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcwExpenseSettlementController.class);

    @Autowired
    private CommonApiService<TcwExpenseSettlement> commonApiService;

    @Autowired
    private TcwExpenseSettlementService tcwExpenseSettlementService;

    @Autowired
    private YspTaskService yspTaskService;

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcwExpenseSettlement setSeachSql(TcwExpenseSettlement cond){

        cond.addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
                .addField("U.UserId + '/' + U.UserName AS _ys_createUserName")//制单人
                .addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("CASE WHEN P.UpdateTime IS NULL AND A.EffectStock = 1 THEN FORMAT(A.UpdateTime, 'yyyy-MM-dd HH:mm:ss') ELSE FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') END auditingTime")//审核时间
                .addLeftJoin("TCW_ExpenseSettlementItem B ON B.Pbid=A.Bid")
                .addField("B.Vgsbmout vgsbmout,B.Vgsjcout vgsjcout,B.Vgsbmin vgsbmin,B.Vgsjcin vgsjcin," +
                        "B.BaseInfoType baseInfoType,B.Amount amount,B.remark premark")

                .addLeftJoin("TS_UserChange QWE ON QWE.Id = A.CreateChangeId")
                .addField("(QWE.UserId + '/' + QWE.UserName) AS _ys_nameLinked")//制单人


                .addLeftJoin("TS_UserInfo CU ON CU.UserId = QWE.UserId")//用户信息表
                .addLeftJoin("TS_OrganizationInfo UO ON UO.Id = CU.OrgId")//用户所属机构
                .addField("QWE.UserId AS userld")
                .addField("CU.OrgId AS orgId")

                .setStatus(1)
                //排序
                .setOrderby("A.Bid DESC");

        cond = commonApiService.dataAuth(MenuId.TCW_ExpenseSettlement, cond);
        return  cond;
    }

    /**
     * 查询
     */
    @RequiresPermissions("tcwExpenseSettlement:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcwExpenseSettlement cond, String conditions
    ){
        try {
            cond = setSeachSql(cond);
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
            LayuiTableVoJA setList = commonApiService.searchLay(cond);

            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }
    /*
     * 新增
     */
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toAdd(HttpServletRequest request, @RequestParam Map<String, Object> params,String bid
    ) {
        try {
            logger.info("费用结算单新增传参：" + params);
            //修改
            return tcwExpenseSettlementService.add(bid,params);
        } catch (Exception e) {
            logger.error("费用结算单新增出错：", e.getMessage(), e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

    /**
     * 修改
     */
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params,String bid,String subData
    ) {
        try {
            logger.info("费用结算单修改传参：" + params);
            //修改
            return tcwExpenseSettlementService.edit(bid,params, MenuId.TCW_ExpenseSettlement);
        } catch (Exception e) {
            logger.error("费用结算单修改出错：", e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }


    /**
     * 删除
     * @throws Exception
     */
    @PostMapping("/delete")
    @ResponseBody
    public R delete(Long id){

        try {
            return tcwExpenseSettlementService.deleteTrue(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("操作失败，请联系客服");
        }
    }
    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcwExpenseSettlement cond, String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.TCW_ExpenseSettlement)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
            //处理数据
            ExportExcelUtils<TcwExpenseSettlement> util = new ExportExcelUtils<>(new TcwExpenseSettlement());
            String toFilePath = util.exportExcel(listData, listField, "费用划拨单");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

    /**
     * 删除列表
     */
    
    @RequestMapping("/toDelByItem")
    @ResponseBody
    public R toDelByItem(HttpServletRequest request,@RequestParam("list") List<String> idList){
        try {
            //删除
            for (int i = 0; i < idList.size(); i++) {
                tcwExpenseSettlementService.toDelByItem(Long.parseLong(idList.get(i)));
            }
            return R.ok();
        } catch (Exception e) {
            logger.error("删除出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }
    /**
     * 流转通过
     */
    
    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            return tcwExpenseSettlementService.flowPass(id, ShiroUtils.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 流转退回
     */

    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){
        try {
            return tcwExpenseSettlementService.flowRefuse(id, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("服务器正在开小差，请联系客服");
        }
    }


    /**
     * 流转驳回
     */

    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){
        try {
            return tcwExpenseSettlementService.flowInit(id, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("服务器正在开小差，请联系客服");
        }
    }


}
        










